<?php


namespace api\channel;


use app\model\BaseSupplier;
use app\model\CouponOrderSid;
use Carbon\Carbon;
use think\Exception;

class ExtendChannleBase
{
    public $apikey = '';

    /**
     * @var BaseSupplier|array|\think\Model
     */
    public $supplierInfo;

    /**
     * 合成 sid
     */
    public function getSid(int $agentId, int $userId = 0, $channel_id = '',$serv_type = 0): string
    {

        $sid = CouponOrderSid::generate($agentId, $channel_id, $userId,0,$serv_type);

        return $sid;

//
//        $res =  $agentId . '_' . $userId;
//
//        if ($channel_id){
//            $res.='_'.$channel_id;
//        }
//
//        return  $res;
    }

    /**
     * 通过 sid 返回 agent_id，user_id
     */
    public function parseSid(string $sid): array
    {
        $sid = explode('_', $sid);
        if (empty($sid[1])) {
            $sid[1] = 0;
        }
        if (empty($sid[2])) {
            $sid[2] = 0;
        }

        return $sid;
    }

    /**
     * 这个不要随意调用，这个方法是给 代理自配接口使用的   ->where('agent_id', '<>', 0)  慎用，会遍历出比较老的供应商接口
     * @param $serv_type
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAgentBaseSupplier($serv_type)
    {

        if ($serv_type == PRODUCT_SECKILL_SERV || $serv_type == PRODUCT_METUAN_SERV) {
            $code = BaseSupplier::CODE_AGENT_MEITUAN_MEITUAN_UNION;
        } elseif ($serv_type == PRODUCT_MEITUAN_TAKEOUT_SERV) {
            $code = BaseSupplier::CODE_AGENT_MEITUAN_MEITUAN_PUB;
        }

        if (empty($code)) {
            throw new Exception('暂未开放该自接程序');
        }

        $baseSuppliers = BaseSupplier::query()
            ->where('code', $code)
            ->where('agent_id', '<>', 0)
            ->select()
            ->each(function (BaseSupplier $baseSupplier) {
                $baseSupplier->append(['last_time']);
            });

        if ($baseSuppliers->isEmpty()) {
            echo '暂无代理商自己配置秘钥的供应商 serv_type:' . $serv_type;
            throw new Exception('暂无代理商自己配置秘钥的供应商');
        }

        $baseSuppliers = collect($baseSuppliers)->order('last_time');

        $baseSupplier = $baseSuppliers->first();

        cache('baseSupplierLast' . $baseSupplier->id, Carbon::now()->format("Y-m-d H:i:s"));

        return $baseSupplier;
    }

}